package com.woniu.postbar.task;

import com.woniu.common.constant.PostBarConstant;
import com.woniu.common.constant.RedisKeyConstant;
import com.woniu.common.utils.StringUtils;
import com.woniu.postbar.entity.dto.PostCommentDTO;
import com.woniu.postbar.entity.vo.PostCommentVO;
import com.woniu.postbar.mapper.PostCommentMapper;
import com.woniu.postbar.service.IPostCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CommentStatus {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PostCommentMapper postCommentMapper;

    /**
     * 每个10秒执行该定时任务
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void queryComment() {
        log.debug("确定添加定时任务开始执行----------------");
        String commentKey = RedisKeyConstant.POST_COMMENT;
        List<PostCommentVO> postCommentVOList = null;
        if (redisTemplate.hasKey(commentKey)) {
            Map<Object, Object> hash = redisTemplate.opsForHash().entries(commentKey);
            // 如果存在添加数据库
            if (hash != null && !hash.isEmpty()) {
                if (hash != null && !hash.isEmpty()) {
                    postCommentVOList = new ArrayList<>();
                    for (Object value : hash.values()) {
                        postCommentVOList.add((PostCommentVO) value);
                    }
                    // 存在则添加进数据库
                    postCommentMapper.insertPostComment(postCommentVOList);
                }
            }
            log.debug("确定添加定时任务结束执行---------------");
        }
    }
}
